class ReliableSubscriber {
private:
    struct mosquitto *mosq;
    uint32_t expected_sequence;
    std::map<uint32_t, OrderedMessage> message_buffer;
    std::set<uint32_t> processed_messages;
    
public:
    void on_message(const struct mosquitto_message *message) override {
        // 检查是否为滞留消息
        if (message->retain) {
            printf("Ignoring retained message\n");
            return;
        }
        
        OrderedMessage ordered_msg;
        if (!deserialize_message(message->payload, message->payloadlen, &ordered_msg)) {
            printf("Failed to deserialize message\n");
            return;
        }
        
        // 验证消息合法性
        if (!validate_message(&ordered_msg)) {
            printf("Message validation failed\n");
            return;
        }
        
        // 检查重复消息
        if (processed_messages.find(ordered_msg.sequence_id) != processed_messages.end()) {
            printf("Duplicate message detected: seq=%u\n", ordered_msg.sequence_id);
            return;
        }
        
        // 处理消息顺序
        process_ordered_message(ordered_msg);
    }
    
private:
    void process_ordered_message(const OrderedMessage& msg) {
        if (msg.sequence_id == expected_sequence) {
            // 正确顺序，立即处理
            handle_message(msg);
            processed_messages.insert(msg.sequence_id);
            expected_sequence++;
            
            // 检查缓冲区中的后续消息
            process_buffered_messages();
        } else if (msg.sequence_id > expected_sequence) {
            // 未来消息，缓存等待
            message_buffer[msg.sequence_id] = msg;
            printf("Buffering out-of-order message: seq=%u, expected=%u\n", 
                   msg.sequence_id, expected_sequence);
        } else {
            // 过期消息，可能是重传
            printf("Received old message: seq=%u, expected=%u\n", 
                   msg.sequence_id, expected_sequence);
        }
    }
    
    void process_buffered_messages() {
        while (message_buffer.find(expected_sequence) != message_buffer.end()) {
            auto msg = message_buffer[expected_sequence];
            handle_message(msg);
            processed_messages.insert(expected_sequence);
            message_buffer.erase(expected_sequence);
            expected_sequence++;
        }
    }
    
    bool validate_message(const OrderedMessage* msg) {
        // 校验和验证
        uint32_t calculated_checksum = calculate_checksum(
            msg->payload, strlen(msg->payload));
        if (calculated_checksum != msg->checksum) {
            return false;
        }
        
        // 时间戳验证（防止过期消息）
        uint64_t current_time = get_current_timestamp();
        if (current_time - msg->timestamp > MAX_MESSAGE_AGE) {
            return false;
        }
        
        return true;
    }
};
